import websocket
from threading import Thread
import time
import sys

gKBs = 0
start_time = time.time()
 
def on_error(ws, error):
  print(error)
 
def on_close(ws):
  print("### closed ###")
 
def on_open(ws):
  def run(*args):
    # send the message, then wait
    # so thread doesn't exit and socket
    # isn't closed
    print("send: setRepeatRequest")
    global start_time
    start_time = time.time()
    ws.send("setRepeatRequest")
  Thread(target=run).start()
 
proflie_ts =  time.time()
def on_data(ws, message, type, flag):
  print("on_data rec: ")
  #print(message)
  global proflie_ts
  global gKBs
  gKBs = gKBs + 1
  speed = gKBs /(time.time() - start_time)
  #print(message)
  print("rec ts_span:",'%.1f' % ((time.time() - proflie_ts)*1000), "speed",'%.3f' % speed, "KB/s")
  proflie_ts = time.time()
 


if __name__ == "__main__":
  print("begin")
  websocket.enableTrace(True)
  host = "ws://192.168.0.102/"
  ws = websocket.WebSocketApp(host,
                #on_message=on_message,
                on_error=on_error,
                on_close=on_close,
                on_data = on_data)
  ws.on_open = on_open
  ws.run_forever()
  time.sleep(10000)
